package com.example.administrator.homeworkintent;
import android.app.Activity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.example.administrator.homeworkintent.IrcDownLoad;
/**
 * Created by Administrator on 2017/11/2.
 */

public  class IrcActivity extends Activity implements GestureDetector.OnGestureListener{
    private TextView tv_lrc;
    private int status;
    private StatusChangedReceiver receiver;
    private LinearLayout linearLayout1;
    private String Irc_data = null;
    private String filename = null;
    private String ircmusicName = null;
    private String ircmusicArtist = null;
    private AsyncDownload asyncDownLoad;
    private GestureDetector gesturedetector;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nextpage);
        tv_lrc = (TextView) findViewById(R.id.songwords);
        linearLayout1 = (LinearLayout) findViewById(R.id.np_linearlayout);
        bindStatusChangedReceiver();
        tv_lrc.setText("当前无歌曲！");
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        gesturedetector = new GestureDetector(this, this);
    }

    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        sendBroadcast(intent);
    }
    class AsyncDownload extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            String url = null;
            try {
                url = IrcDownLoad.getSongIRCURL(params[0], params[1]);
                Irc_data = IrcDownLoad.getHtmlCode(url);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            return Irc_data;
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            if (result == null) {
                tv_lrc.setText("当前没有歌词");
            } else {
                try {
                    // 写入文件
                    FileOutputStream outputStream = IrcActivity.this.openFileOutput(filename, Context.MODE_PRIVATE);
                    outputStream.write(result.getBytes());
                    outputStream.close();
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String string = drawLrcLoad(filename);
                tv_lrc.setText(string);
            }
        }
    }
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    ircmusicName = intent.getStringExtra("musicName");
                    ircmusicArtist = intent.getStringExtra("musicArtist");
                    IrcActivity.this.setTitle(ircmusicName + " - " + ircmusicArtist);
                    get_lrc(IrcActivity.this);
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        if(asyncDownLoad != null && asyncDownLoad.isCancelled()){
            asyncDownLoad.cancel(true);
        }
    }
    @Override
    public boolean onFling(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) {
        if(arg1.getX()-arg0.getX()>150)
        {
            finish();
            overridePendingTransition(R.anim.to_right_enter, R.anim.to_right_exit);
            Toast.makeText(getApplicationContext(), "歌词", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
    private String drawLrcLoad(String filename){
        String lrc_word=" ";
        Pattern pattern = Pattern.compile("\\[\\d{2}:\\d{2}.\\d{2}\\]");
        try {
            File file=new File(getApplicationContext().getFilesDir() + "/"
                    + filename);
            System.out.println(file.getPath());
            BufferedReader reader=new BufferedReader(new FileReader(file));
            String line = "";
                while ((line = reader.readLine()) != null) {
                    Matcher m = pattern.matcher(line);
                    line = m.replaceAll("");
                    line = line.replace("[ti:", "");
                    line = line.replace("[ar:", "");
                    line = line.replace("[al:", "");
                    line = line.replace("[by:", "");
                    line = line.replace("[i:", "");
                    line = line.replace("]", "");
                    line = line.contains("offset") ? "" : line;
                    line = line.replace("null", "");
                    lrc_word += line + "\n";
                }
                return lrc_word;
            } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public boolean dispatchTouchEvent(MotionEvent event)
    {
        if(gesturedetector.onTouchEvent(event))
        {
            event.setAction(MotionEvent.ACTION_CANCEL);
        }
        return super.dispatchTouchEvent(event);
    }
    private void get_lrc(Context context) {
        String files[] = context.fileList();
        if (ircmusicName != null) {
            filename = ircmusicName + ".lrc";
            List<String> filelist = Arrays.asList(files);
            if (filelist.contains(filename)) {
                Log.i("TAG", "has lrc file!");
                String string=drawLrcLoad(filename);
                tv_lrc.setText(string);
            } else {
                ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo info = cwjManager.getActiveNetworkInfo();
                if (info != null && info.isAvailable()) {
                    Log.i("TAG", "has not lrc file!");
                    asyncDownLoad = new AsyncDownload();
                    asyncDownLoad.execute(IrcDownLoad.IRC_SEARCH_URL, ircmusicName);
                } else {
                    Toast.makeText(getApplicationContext(), "当前网络不给力哦，请检测网络配置！", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        return gesturedetector.onTouchEvent(event);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }
}
